setwd("/Users/mihwa/Google drive/Matching_optional protocol")  
data<-read.dta("/Users/mihwa/Google drive/Matching_optional protocol/matchcat.dta")
attach(data)

# The following will run a caliper matching algorithm on the collapsed CAT data.
# data will run matching diagnostics.
matchcat_II <- matchit(catboth ~ catonly+ p_polity2+ trans+ lnwdi_gdpc+ wdi_gdpgr+ ciri_disap+ ciri_kill+ ciri_polpris+ ciri_tort+ ucdp_type3+ LINVP+ eeuro+ lame+ meast+ ssafr+ easia+ seasia+ sasia+ pacific+ caribbean, data=data, method="genetic", estimand="ATT", pop.size=200, int.seed=9)
matcheddata_II <- match.data(matchcat_II)
write.dta(matcheddata_II, file="matchedcat_II.dta")

## balance checking

covar<-data[,c("catonly", "p_polity2", "trans","lnwdi_gdpc","wdi_gdpgr", "ciri_disap", "ciri_kill", "ciri_polpris", "ciri_tort", "ucdp_type3",
               "LINVP","eeuro", "lame", "meast", "ssafr", "easia", "seasia", "sasia", "pacific", "caribbean")]

fmla <- as.formula(paste("catboth~",paste(names(covar),collapse="+")))

g.weights <- GenMatch(Tr=catboth, X=covar, BalanceMatrix=covar, estimand="ATT",  pop.size= 200,int.seed=9)
mout.gm <-  Match(INVP, catboth,covar,BiasAdjust=F,Weight.matrix=g.weights, estimand="ATT")

bout.gm <- MatchBalance(fmla,match.out = mout.gm,print.level=0,ks=FALSE)
bal.gm <- baltest.collect(matchbal.out=bout.gm,var.names=colnames(covar),after=TRUE)
bal.gm2 <- baltest.collect(matchbal.out=bout.gm,var.names=colnames(covar),after=FALSE)

bal.gm=bal.gm[,c("mean.Tr","mean.Co","sdiff.pooled","T pval")]
bal.gm2<-bal.gm2[,c("mean.Tr","mean.Co","sdiff.pooled","T pval")]
bal=cbind(bal.gm2,bal.gm)
bal=round(bal,3)
bal=data.frame(bal)
#colnames(bal) <- c("var", "mean_Tr","mean_Co","sdiff_pooled","pval","mean_Tr2","mean_Co2","sdiff_pooled2","pval2")

write.csv(bal,"bal_cat_II.csv")

